import { DeleteOutlined, EditOutlined } from '@ant-design/icons';
import { Space, Button, Tooltip, Select, Dropdown } from "antd";
import { useEffect, useState } from "react";
import { useTable, useTableDialog } from "@/hooks/useTable";
import { useFormDialog } from "@/hooks/useForm";
import FormModal from "@/component/FormModal";
import CloudTable from "@/component/CloudTable";
import { page, del, batDel, save, edit, insertGroupStaff, findStaffByGroupId, delStaffByGroupId } from "@/views/attendance/group/api";
import { page as pageCalendar } from "@/views/attendance/calendar/api";
import { page as pageShift } from "@/views/attendance/shift/api";
import { page as pageWork } from "@/views/attendance/work/api";
import { page as pageStaff } from "@/views/employee/staff/api";
import { STATUS_ENUMS, STATUS_OPTIONS } from "@/views/attendance/group/data";
import TableModal from '@/component/TableModal';

const Group = () => {

    // -------------------
    // ---   员工操作   ---
    // -------------------

    // 员工下拉搜索
    const [staffOptions, setStaffOptions] = useState([]);
    const onSearchStaffHandle = (val) => {
        let query = { params: [{ field: 'name', expr: 'LIKE_LEFT', value: val }] };
        pageStaff(query).then(resp => {
            let options = resp?.data?.records.map(item => ({
                label: item.name + '(' + item.code + ')',
                value: item.id,
            }));
            setStaffOptions(options);
        });
    }

    const onStaffFormCallback = (model) => {
        let query = {
            ...model,
            groupId: staffTableModal.row.id
        };
        staffForm.onSubmit(query, staffTableModal.onReload);
    }

    // 表单
    const staffForm = useFormDialog({
        save: insertGroupStaff,
        edit: undefined,
        callback: onStaffFormCallback,
        items: [
            {
                label: '员工',
                name: 'staffId',
                render: <Select
                    showSearch
                    allowClear
                    placeholder="请输入姓名"
                    optionFilterProp="label"
                    filterOption={false}
                    onSearch={(val) => onSearchStaffHandle(val)}
                    options={staffOptions}
                />
            },
        ],
    });

    // 表格
    const staffColumns = [
        {
            title: '#',
            key: 'index',
            width: 50,
            align: 'center',
            fixed: 'left',
            render: (val, record, index) => {
                return index + 1;
            }
        },
        {
            title: '员工编号',
            dataIndex: 'code',
            key: 'code',
            ellipsis: true,
            width: 'auto',
            search: 'default',
        },
        {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
            ellipsis: true,
            width: 'auto',
            search: 'default',
        },
    ];

    const staffTools = () => (
        <Space>
            <Button type="primary" size='small' onClick={() => staffForm.isOpenDialog(undefined, '新增')}>新增</Button>
            <Button type='dashed'  size='small' style={{ color: 'red' }} onClick={() => onRemoveGroupStaff()}>删除</Button>
        </Space>
    );

    const staffTableModal = useTableDialog({
        title: '员工',
        reload: findStaffByGroupId,
        remove: delStaffByGroupId,
        tools: staffTools,
        columns: staffColumns,
    });

    const onRemoveGroupStaff = () => {
        let query = {
            id: staffTableModal.row.id,
            data: staffTableModal.selected,
        }
        staffTableModal.onRemove(query, '确定要删除选中的员工吗？');
        // 清空选中数据。防止刚删除，又添加相同数据时，被默认选中
        staffTableModal.resetSelected([]);
    }

    // -------------------
    // ---   表单操作   ---
    // -------------------

    // 日历下拉搜索框
    const [calendarOptions, setCalendarOptions] = useState([]);
    const onSearchCalendarHandle = (val) => {
        let query = { params: [{ field: 'name', expr: 'LIKE_LEFT', value: val }] };
        pageCalendar(query).then(resp => {
            let options = resp?.data?.records.map(item => ({
                label: item.name,
                value: item.id,
            }));
            setCalendarOptions(options);
        });
    }

    // 班次下拉搜索框
    const [shiftOptions, setShiftOptions] = useState([]);
    const onSearchShiftHandle = (val) => {
        let query = { params: [{ field: 'name', expr: 'LIKE_LEFT', value: val }] };
        pageShift(query).then(resp => {
            let options = resp?.data?.records.map(item => ({
                label: item.name,
                value: item.id,
            }));
            setShiftOptions(options);
        });
    }

    // 工制下拉搜索框
    const [workOptions, setWorkOptions] = useState([]);
    const onSearchWorkHandle = (val) => {
        let query = { params: [{ field: 'name', expr: 'LIKE_LEFT', value: val }] };
        pageWork(query).then(resp => {
            let options = resp?.data?.records.map(item => ({
                label: item.name,
                value: item.id,
            }));
            setWorkOptions(options);
        });
    }

    // 表单提交
    const onGroupFormCallback = (model) => {
        groupForm.onSubmit(model, groupTable.onReload);
    }

    // 表单设置
    const groupForm = useFormDialog({
        save: save,
        edit: edit,
        callback: onGroupFormCallback,
        items: [
            {
                label: '组名',
                name: 'name',
            },
            {
                label: '日历',
                name: 'calendarId',
                render: <Select
                    showSearch
                    allowClear
                    placeholder="请选择日历"
                    optionFilterProp="label"
                    filterOption={false}
                    onSearch={(val) => onSearchCalendarHandle(val)}
                    options={calendarOptions}
                />
            },
            {
                label: '班次',
                name: 'shiftId',
                render: <Select
                    showSearch
                    allowClear
                    placeholder="请选择班次"
                    optionFilterProp="label"
                    filterOption={false}
                    onSearch={(val) => onSearchShiftHandle(val)}
                    options={shiftOptions}
                />
            },
            {
                label: '工制',
                name: 'systemId',
                render: <Select
                    showSearch
                    allowClear
                    placeholder="请选择日历"
                    optionFilterProp="label"
                    filterOption={false}
                    onSearch={(val) => onSearchWorkHandle(val)}
                    options={workOptions}
                />
            },
            {
                label: '说明',
                name: 'describe',
            },
            {
                label: '状态',
                name: 'status',
                render: <Select placeholder='请选择状态' options={STATUS_OPTIONS()} />,
            },
        ],
    });

    // -------------------
    // ---   表格操作   ---
    // -------------------

    // 表格自定义按钮
    const tools = () => {
        return (
            <Space>
                <Button type="primary" onClick={() => onOpenGroupForm(undefined)}>新增</Button>
                <Button type='dashed' style={{ color: 'red' }} onClick={() => groupTable.onBatchRemove(groupTable.selected)}>删除</Button>
            </Space>
        );
    }

    const groupTableOperator = (val) => {
        return ([
            {
                label: <a href='#' style={{ color: '#7d6cff' }} onClick={() => staffTableModal.isOpenDialog({ id: val, data: {} })}>员工</a>,
                key: 'staff',
            },
        ]);
    }

    // 表格列
    const columns = [
        {
            title: '#',
            key: 'index',
            width: 50,
            align: 'center',
            fixed: 'left',
            render: (val, record, index) => {
                return index + 1;
            }
        },
        {
            title: '组名',
            dataIndex: 'name',
            key: 'name',
            ellipsis: true,
            search: 'default',
        },
        {
            title: '日历',
            dataIndex: 'calendarName',
            key: 'calendarName',
            ellipsis: true,
            search: 'default',
        },
        {
            title: '班次',
            dataIndex: 'shiftName',
            key: 'shiftName',
            ellipsis: true,
            search: 'default',
        },
        {
            title: '工制',
            dataIndex: 'systemName',
            key: 'systemName',
            ellipsis: true,
            search: 'default',
        },
        {
            title: '说明',
            dataIndex: 'describe',
            key: 'describe',
            ellipsis: true,
            search: 'default',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 'auto',
            search: 'selected',
            options: STATUS_OPTIONS(),
            render: (val) => STATUS_ENUMS[val] || ''
        },
        {
            title: '操作',
            dataIndex: 'id',
            width: 120,
            align: 'center',
            fixed: 'right',
            render: (val, row) => {
                return (
                    <div>
                        <Tooltip title="编辑">
                            <Button type="text" size="small" icon={<EditOutlined />} style={{ margin: '0 4px', color: 'blue' }} onClick={() => onOpenGroupForm(row)} />
                        </Tooltip>
                        <Tooltip title="删除">
                            <Button type="text" size="small" icon={<DeleteOutlined />} style={{ margin: '0 4px', color: 'red' }} onClick={() => groupTable.onRemove(val)} />
                        </Tooltip>
                        <Dropdown menu={{ items: groupTableOperator(val) }} placement='bottomRight'>
                            <a style={{ margin: '0 8px' }} onClick={e => e.preventDefault()}>
                                <Space>···</Space>
                            </a>
                        </Dropdown>
                    </div>
                )
            }
        }
    ];
    // 表格设置
    const groupTable = useTable({
        reload: page,
        remove: del,
        batchRemove: batDel,
        tools,
        columns,
    });

    // -------------------
    // ---   方法事件   ---
    // -------------------

    const onOpenGroupForm = (model) => {
        if (model?.id) {
            setCalendarOptions([{ label: model.calendarName, value: model.calendarId }]);
            setShiftOptions([{ label: model.shiftName, value: model.shiftId }]);
            setWorkOptions([{ label: model.systemName, value: model.systemId }]);
            groupForm.isOpenDialog(model, '编辑');
        } else {
            setCalendarOptions([]);
            setShiftOptions([]);
            setWorkOptions([]);
            groupForm.isOpenDialog(model, '新增');
        }
    }

    useEffect(() => {
        groupTable.onReload();
    }, []);

    return (
        <>
            <CloudTable props={groupTable} />
            <FormModal props={groupForm} />
            <TableModal props={staffTableModal} />
            <FormModal props={staffForm} />
        </>
    );
}

export default Group;